/*
 * 精品爆款
 * Author:zql
 * Date:2016/12/16
 */
$(function(){
	//表格
	$('#table1').datagrid({
		width:'100%',
		height:'340px',
		fitColumns:true,
		pagination:true,
		rownumbers:false,
		singleSelect:true,
		loadMsg:"正在加载，请稍等...",
		url:'../productManage/products',
		queryParams:common.getDataGridUrlQueryParams(),
		columns:[[
			{field:'sort',title:'展位序号',width:80,align:'center'},
			{field:'productImg',title:'商品图片',width:100,align:'center'},
			{field:'productName',title:'商品名称',width:180,align:'center'},
			{field:'normalPrice',title:'商品原价',width:80,align:'center',formatter:common.priceFormatter},
			{field:'sailPrice',title:'商品现价',width:80,align:'center',formatter:common.priceFormatter},
			{field:'superPrice',title:'商品超低价',width:80,align:'center',formatter:common.priceFormatter},
			{field:'highestComm',title:'返佣金额',width:80,align:'center',formatter:common.priceFormatter},
			{field:'operate',title:'操作',width:160,align:'center',fixed:'true',
				formatter:function (value,row,index){
					//获取上下架状态
					var statuspan = $('.sel-status span.active');
					var status = $(statuspan).attr("status");
					var operate = "";
					if(status==0){//未上架
						operate = "<a href='javascript:;' opera-view rowIndex='"+index+"'>查看</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='javascript:;' opera-edit rowIndex='"+index+"'>编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='javascript:;' opera-up rowIndex='"+index+"'>上架</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='javascript:;' opera-del rowIndex='"+index+"'>删除</a>";
					}else{
						operate = "<a href='javascript:;' opera-view rowIndex='"+index+"'>查看</a>&nbsp;&nbsp;&nbsp;&nbsp;" +
							"<a href='javascript:;' opera-down rowIndex='"+index+"'>下架</a>&nbsp;&nbsp;&nbsp;&nbsp;";
					}
					
					return operate;
				}
			},
			{field:'sorting',title:'排序',width:80,align:'center',hidden:"true",fixed:'true',
				formatter:function(value,row,index){
					//获取总数
					var sortting = "";
					if(index==0){
						sortting = "<span class='btn-down btn-down-red' rowIndex='"+index+"'></span>";
					}else if(index==(row.count-1)){
						sortting = "<span class='btn-up ' rowIndex='"+index+"'></span>";
					}else{
						sortting = "<span class='btn-up ' rowIndex='"+index+"'></span>&nbsp;&nbsp;&nbsp;" +
							"<span class='btn-down btn-down-red' rowIndex='"+index+"'></span>";
					}
					return sortting;
				}
			}
		]]
	});

	$('#table1').datagrid('getPager').pagination({
		beforePageText: '第',
		afterPageText: '页，共 {pages} 页',   
		displayMsg: '当前显示 {from} - {to} 条记录   共 {total} 条记录'
	});

	//新增产品弹窗
	$(document).on('click','[add-btn] a.active',function(){
		//清空原有数据
		common.cleanProductInfo();
		$('[add-product]').dlog({
			title:'新增产品',
			width:700,
			height:450
		});
		return false;
	});
	$('[btn-cancel-add]').on('click',function(){
		$('[add-product]')._dlogclose();
		return false;
	});
	
	//编辑弹框
	$(document).on('click','[opera-edit]',function(){
		var rowIndex = $(this).attr("rowIndex");
		var rows = $('#table1').datagrid('getRows');
		$('[add-product]').dlog({
			title:'编辑产品',
			width:700,
			height:450
		});
		//设置值
		for(i=0;i<rows.length;i++){
			var row = rows[i];
			var index = $('#table1').datagrid('getRowIndex',row);
			if(index == rowIndex){
				common.showEditProductInfo(row);
				if(row.priceType==1){//原价+现价
					$('#sail-price-model').attr("checked","checked");
					$('#super-price-model').removeAttr("checked");
				}else{
					$('#super-price-model').attr("checked","checked");
					$('#sail-price-model').removeAttr("checked");
				}
			}
		}
		return false;
	});
	
	//查看弹窗
	$(document).on('click','[opera-view]',function(){
		var rowIndex = $(this).attr("rowIndex");
		var rows = $('#table1').datagrid('getRows');
		$('[loo-up-product]').dlog({
			title:'查看产品',
			width:700,
			height:450
		});
		//设置显示值
		for(i=0;i<rows.length;i++){
			var row = rows[i];
			var index = $('#table1').datagrid('getRowIndex',row);
			if(index == rowIndex){
				common.showProductInfo(row);
				if(row.priceType==1){//原价+现价
					$('[superModel]').hide();
					$('[sailPriceModel]').show();
				}else{
					$('[superModel]').show();
					$('[sailPriceModel]').hide();
				}
			}
		}
		return false;
	});
	$('[btn-confirm-look]').on('click',function(){
		$('[loo-up-product]')._dlogclose();
		return false;
	});
	
	
	/*
	 * 图片上传
	 * Author:baiyg
	 * Date:2015/9/8
	 */
	$('#uploadImg').on('change',function(e){
		// 判断上传文件格式
		if(($(this).val().indexOf('.png') == -1 && $(this).val().indexOf('.jpg') == -1)){
			var oSpan=$('<span class="text2">此格式不支持</span>'),
				mask=$('<span class="mask"></span>');
			$(this).parent().find('.text1').hide();
			$(this).parent().prepend(oSpan);
			$(this).parent().append(mask);
			return false;
		}else if($(this).val().indexOf('.png') != -1){
			var src=$(this).val().match(/\w+.png/);
		}else if($(this).val().indexOf('.jpg') != -1){
			var src=$(this).val().match(/\w+.jpg/);
		}
		var html = '<div class="upLoadPar" name="module-layout"><span class="img"></span><i class="del"></i></div>';
		//var newImg=$('<img src="'+picStr+'">');
		var scale=$('<div class="uploadScale"><span class="tip">上传中，请稍后</span><div class="load"></div></div>');
		var mask=$('<span class="mask"></span>');
		var len = $('.upLoadPar').length;
		$(this).parents('.add-pic').addClass('undis');
		$(this).parent().find('.mask').remove();
		$(this).parent().find('.text2').remove();
		$(this).parent().find('.text1').show();
		$('[name="upLoadWrap"]').append(html);
		$('[name="upLoadWrap"] .upLoadPar').eq(len).find('.img').append(scale);
		$('[name="upLoadWrap"] .upLoadPar').eq(len).find('.img').append(mask);
		preview(e.target.files[0],scale);
		$(scale).find('.load').animate({'width':'100%'},2000,function(){
			$(scale).parent().attr('name','move-layout');
			$(scale).remove();
			$('.mask').remove();
			$('.add-pic').removeClass('undis');
		});
		if($('[name="upLoadWrap"] .upLoadPar').length == 1){
			$(this).parents('.add-pic').hide();
		}
	});
	
	//H5预览图片
	function preview(file,scale) {
        var img = new Image(), url = img.src = URL.createObjectURL(file)
        var $img = $(img)
        img.onload = function() {
        	$(scale).parent().append($img);
            URL.revokeObjectURL(url)
        }
    }
	
	 //显示删除按钮
	$(document).on({
		mouseover:function(){
			if($(this).find('img').length > 0){
				$(this).find('.del').show();
			}
		},
		mouseout:function(){
			$(this).find('.del').hide();
		}
	},'[name="upLoadWrap"] .upLoadPar');

	 $(document).on('click','[name="upLoadWrap"] .upLoadPar .del',function(){
		 var _this = this;
		 $(this).parent('.upLoadPar').find('img').animate({'opacity':'0'},500,function(){
			$(_this).parent('.upLoadPar').remove();
			$('.add-pic').show();
		 });
	 });

	 //确认添加/编辑
	 $(document).on('click','[btn-confirm-add]',function(){
		//获取信息
		 var productInfo = common.getSaveProductInfo();
		 var url = "";
		 //判断是新增还是编辑
		 var productId = convertStr($('#productId').val())
		 var content = "";
		 if(productId=="" || productId==0){//新增
			 url = "../productManage/addProduct";
			 content = "确认添加此商品？";
		 }else{
			 url = "../productManage/editProduct";
			 content = "确认编辑此商品？";
			 productInfo.append('productId',productId);
		 }
		 $.msgr({
			title:'确认提示',
			icon:'question',
			content:content,
			ok_fn:function(){
				//添加商品
				$.ajax({
				   type: "POST",
				   url: url,
				   data: productInfo,
				   dataType:"json",
				   async:false,
				   cache: false,
				   contentType: false,        //不可缺参数
				   processData: false,        //不可缺参数
				   success: function(msg){
					 $('#table1').datagrid('reload');
				     $('[add-product]')._dlogclose();
				   },
				   error:function (XMLHttpRequest, textStatus, errorThrown) {
					   // 通常 textStatus 和 errorThrown 之中
					   // 只有一个会包含信息
					   var errmsg = XMLHttpRequest.responseJSON.message;
					   $.msgr({
							title:'错误提示',
							icon:'error',
							content:errmsg,
							cancelButton:false
					   });
					   //console.log(textStatus);
					   //console.log(errorThrown);
					}
				});
				return false;
			}
		});
	 });
	 

	// 上移按钮
	$(document).on('click', '[class="btn-up "]', function() {
		var rowIndex = $(this).attr("rowIndex");
		var sortType = 1;//1：上移；2：下移
		var moduleId = '4005';
		common.modifyProductSort(rowIndex, sortType, moduleId);
	});

	// 下移按钮
	$(document).on('click', '[class="btn-down btn-down-red"]', function() {
		var rowIndex = $(this).attr("rowIndex");
		var sortType = 2;//1：上移；2：下移
		var moduleId = '4005';
		common.modifyProductSort(rowIndex, sortType, moduleId);
	});
});